package com.yitongmao.common.sharesdk;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.mob.tools.utils.UIHandler;
import com.yitongmao.common.AppConstants;
import com.yitongmao.common.FileUtils;
import com.yitongmao.common.reminder.ReaderApplication;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.util.Loger;
import com.yitongmao.util.StringUtils;
import com.yitongmao.yitmfruit.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.system.email.Email;
import cn.sharesdk.system.text.ShortMessage;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;



/**
 * 分享和业务结合类，纯粹分享的参考ShareSDKUtils.java
 */
public class ShareAndBusnessUtils implements PlatformActionListener, Handler.Callback {


    private volatile static ShareAndBusnessUtils instance;
    private Context context;
    private static final int MSG_TOAST = 1;
    private static final int MSG_ACTION_CCALLBACK = 2;
    private static final int MSG_CANCEL_NOTIFY = 3;

    public String id;
    public String type;
    public String eventType;
    public String shareWhere;

    public static ShareAndBusnessUtils getInstance(Context context) {
        if (instance == null) {
            synchronized (ShareAndBusnessUtils.class) {
                if (instance == null) {
                    instance = new ShareAndBusnessUtils(context);
                }
            }
        }
        return instance;
    }

    public void setBusnessParames(String id, String type, String eventType) {
        this.id = id;
        this.type = type;
        this.eventType = eventType;
    }

    private ShareAndBusnessUtils() {
    }

    private ShareAndBusnessUtils(Context context) {
        this.context = context;
        initData();
    }

    /**
     * 获取分享平台
     */
    private void initData() {
        ShareSDK.initSDK(context);
        final Platform[][] platformList = {null};
        if (platformList[0] == null || platformList[0].length == 0) {
            new Thread() {
                @Override
                public void run() {
                    platformList[0] = ShareSDK.getPlatformList(context);
                }
            }.start();
        }
        // 禁用SSO
        Platform weibo = ShareSDK.getPlatform(context, SinaWeibo.NAME);
        if (weibo != null) {
            weibo.SSOSetting(false);
        }
    }
//    dfdffd
    /**
     * 分享
     *
     * @param text      分享文本，所有平台都需要这个字段,标题
     * @param title     标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
     * @param imagePath 图片的本地路径，Linked-In以外的平台都支持此参数
     * @param imageUrl
     * @param url       url仅在微信（包括好友和朋友圈）中使用
     */
    public void showShare(final String text, final String title, String imagePath, final String imageUrl, final String url) {
        if (context == null) {
            return;
        }

        if (imagePath == null) {
            imagePath = "";
        }
//        if (url == null) {
//            url = "";
//        }
        if (TextUtils.isEmpty(title) || title.equalsIgnoreCase("null")) {
            Toast.makeText(context, ReaderApplication.getInstace().getResources().getString(R.string.app_name), Toast.LENGTH_SHORT).show();
            return;
        }
        // 初始化ShareSDK
        ShareSDK.initSDK(context);
        final OnekeyShare oks = new OnekeyShare();
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//        if (!TextUtils.isEmpty(title)) {
//            oks.setTitle(title);
//        }
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        /*oks.setTitleUrl(url);
        oks.setUrl(url);*/
        // text是分享文本，所有平台都需要这个字段
      /*  if (!TextUtils.isEmpty(text)) {
            oks.setText(text);
        }*/
        // imagePath是图片的本地路径，sdcard卡中图片地址
        if (!TextUtils.isEmpty(imagePath)) {
            oks.setImagePath(imagePath);
        }
        // imageUrl是图片的网络路径，新浪微博、人人网、微信
        if (!TextUtils.isEmpty(imageUrl)) {
            oks.setImageUrl(imageUrl);
        }

        //如果图片都为空，则默认为图片icon
        if (TextUtils.isEmpty(imagePath) && TextUtils.isEmpty(imageUrl)) {

            String path = FileUtils.ImageCacheSD + "/share_image/";
            String iconPath = path + "share_icon.png";

            File dirFile = new File(path);
            dirFile.mkdirs();
            File icon = new File(iconPath);
            if (!icon.exists()) {
                try {
                    icon.createNewFile();
                    Bitmap pic = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
                    FileOutputStream fos = new FileOutputStream(icon);
                    pic.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            oks.setImagePath(iconPath);
        }
        // url仅在微信（包括好友和朋友圈）中使用
       /* if (!TextUtils.isEmpty(url)) {
            oks.setUrl(url);
        }*/

        //分享到那个平台


        //自定义分享模块：拷贝链接
        Bitmap logo = BitmapFactory.decodeResource(context.getResources(),
                R.mipmap.ic_launcher);
        String label = context.getResources().getString(
                R.string.logo_share_copylink);
        final String finalUrl = title + "\n" + url;
        View.OnClickListener listener = new View.OnClickListener() {
            @SuppressLint("NewApi")
            public void onClick(View v) {
                String displayStr = finalUrl;

                ClipboardManager cmb = (ClipboardManager) context
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText(
                        context.getString(R.string.app_name),
                        displayStr);
                cmb.setPrimaryClip(clip);
                Toast.makeText(context, ReaderApplication.getInstace().getResources().getString(R.string.share_title_already_copy),
                        Toast.LENGTH_SHORT).show();
            }
        };
        oks.setCustomerLogo(logo, label, listener);
        final String finalUrl2 = url;
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, Platform.ShareParams paramsToShare) {
                String platFormName = platform.getName();
                // oks.setTitle(getString(R.string.share));
                // title标题，印象笔记、邮箱、信息、微信好友、人人网和QQ空间使用
                Loger.e("title", title + "");
                Loger.e("text", text + "");
                Loger.e("finalUrl2", finalUrl2 + "");
                if (Email.NAME.equals(platFormName) || ShortMessage.NAME.equals(platFormName)) {
                    paramsToShare.setTitle(title);
                }

                // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
                //QQ空间分享
                if (QZone.NAME.equals(platFormName)) {

                    if (StringUtils.isBlank(text)) {
                        paramsToShare.setText(title);
                    } else {
                        paramsToShare.setTitle(title);
                        paramsToShare.setText(text);
                    }

                    paramsToShare.setTitleUrl(finalUrl2);
                    // site是分享此内容的网站名称，仅在QQ空间使用
                    paramsToShare.setSite(ReaderApplication.getInstace().getResources().getString(R.string.app_name));
                    // siteUrl是分享此内容的网站地址，仅在QQ空间使用
                    paramsToShare.setSiteUrl(ReaderApplication.getInstace().getResources().getString(R.string.app_name));
                    if (!TextUtils.isEmpty(imageUrl)) {
                        paramsToShare.setImageUrl(imageUrl);
                    }
                }
                //QQ分享
                if (QQ.NAME.equals(platFormName)) {
                    paramsToShare.setTitle(title);
                    paramsToShare.setText(text);
                    paramsToShare.setTitleUrl(url);
                    if (!TextUtils.isEmpty(imageUrl)) {
                        paramsToShare.setImageUrl(imageUrl);
                    }
                }
                //微博分享
                if (SinaWeibo.NAME.equals(platFormName)) {
                    paramsToShare.setText(title + " " + finalUrl2);
                }
                //微信朋友分享
                if (Wechat.NAME.equals(platFormName)) {
                    paramsToShare.setTitle(title);
                    if (!StringUtils.isBlank(text)) {
                        paramsToShare.setText(text);
                    }
                    if (!TextUtils.isEmpty(imageUrl)) {
                        paramsToShare.setImageUrl(imageUrl);
                    }
                }
                //微信朋友圈分享
                if (WechatMoments.NAME.equals(platFormName)) {
                    paramsToShare.setTitle(title);
                    paramsToShare.setText(text);
                    if (!TextUtils.isEmpty(imageUrl)) {
                        paramsToShare.setImageUrl(imageUrl);
                    }
                }

                // url仅在微信（包括好友和朋友圈）中使用
                if (Wechat.NAME.equals(platFormName) || WechatMoments.NAME.equals(platFormName)) {
                    paramsToShare.setUrl(finalUrl2);
                    paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                }

                //信息分享
                if (ShortMessage.NAME.equals(platform.getName())) {
                    paramsToShare.setText(finalUrl);
                    paramsToShare.setImageUrl(null);
                }
                //邮件分享
                if (Email.NAME.equals(platform.getName())) {
                    paramsToShare.setText(finalUrl);
                    paramsToShare.setImageUrl(null);
                }
            }

            private boolean needTextUrl(String name) {
                if ("Wechat".equals(name)) {
                    return false;
                } else if ("WechatMoments".equals(name)) {
                    return false;
                } else if (QQ.NAME.equals(name)) {
                    return false;
                } else if (QZone.NAME.equals(name)) {
                    return false;
                }
                return true;
            }
        });

        oks.setSilent(false);
        // 设置自定义的外部回调
        oks.setCallback(this);
        oks.show(context);
    }

//    public void showShare(final String text, final String title, String imagePath, String imageUrl, String url,String sid, PlatformActionListener callbackListener) {
//        if (callbackListener == null) {
//            showShare(text, title, imagePath, imageUrl, url,sid);
//        } else {
//            if (context == null) {
//                return;
//            }
//
//            if (imagePath == null) {
//                imagePath = "";
//            }
//            if (imageUrl == null) {
//                imageUrl = "";
//            }
//            if (url == null) {
//                url = "";
//            }
//            if (TextUtils.isEmpty(text) || text.equalsIgnoreCase("null")) {
//                Toast.makeText(context, "标题不能为空", Toast.LENGTH_SHORT).show();
//                return;
//            }
//            // 初始化ShareSDK
//            ShareSDK.initSDK(context);
//            OnekeyShare oks = new OnekeyShare();
//            // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//            if (!TextUtils.isEmpty(title)) {
//                oks.setTitle(title);
//            }
//            // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
//            oks.setTitleUrl(url);
//            oks.setUrl(url);
//            // text是分享文本，所有平台都需要这个字段
//            if (!TextUtils.isEmpty(text)) {
//                oks.setText(text);
//            }
//            // imagePath是图片的本地路径，sdcard卡中图片地址
//            if (!TextUtils.isEmpty(imagePath) && !URLUtil.isNetworkUrl(imageUrl)) {
//                oks.setImagePath(imagePath);
//            }
//            // imageUrl是图片的网络路径，新浪微博、人人网、微信
//            if (!TextUtils.isEmpty(imageUrl) && URLUtil.isNetworkUrl(imageUrl)) {
//                oks.setImageUrl(imageUrl);
//            }
//
//            //如果图片都为空，则默认为图片icon
//            if (TextUtils.isEmpty(imagePath) && TextUtils.isEmpty(imageUrl)) {
//
//                String path = getPath() + "//Founder/share_image/";
//                String iconPath = path + "share_icon.png";
//
//                File dirFile = new File(path);
//                dirFile.mkdirs();
//                File icon = new File(iconPath);
//                if (!icon.exists()) {
//                    try {
//                        icon.createNewFile();
//                        Bitmap pic = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
//                        FileOutputStream fos = new FileOutputStream(icon);
//                        pic.compress(Bitmap.CompressFormat.PNG, 100, fos);
//                        fos.flush();
//                        fos.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//                oks.setImagePath(iconPath);
//            }
//            // url仅在微信（包括好友和朋友圈）中使用
//            if (!TextUtils.isEmpty(url) && URLUtil.isNetworkUrl(url)) {
//                oks.setUrl(url);
//            }
//            //自定义分享模块：拷贝链接
//            Bitmap logo = BitmapFactory.decodeResource(context.getResources(),
//                    R.drawable.logo_share_copylink);
//            String label = context.getResources().getString(
//                    R.string.logo_share_copylink);
//            final String finalUrl = text + "\n" + url;
//            View.OnClickListener listener = new View.OnClickListener() {
//                @SuppressLint("NewApi")
//                public void onClick(View v) {
//                    String displayStr = finalUrl;
//
//                    ClipboardManager cmb = (ClipboardManager) context
//                            .getSystemService(Context.CLIPBOARD_SERVICE);
//                    ClipData clip = ClipData.newPlainText(
//                            context.getString(R.string.app_name),
//                            displayStr);
//                    cmb.setPrimaryClip(clip);
//                    Toast.makeText(context, "所选内容已成功复制到剪贴板",
//                            Toast.LENGTH_SHORT).show();
//
//                }
//            };
//            oks.setCustomerLogo(logo, label, listener);
//            final String finalUrl1 = url;
//            oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
//                @Override
//                public void onShare(Platform platform, Platform.ShareParams paramsToShare) {
//                    if (cn.sharesdk.system.text.ShortMessage.NAME.equals(platform.getName())) {
//                        paramsToShare.setImageUrl(null);
//                    } else if (cn.sharesdk.system.email.Email.NAME.equals(platform.getName())) {
//                        paramsToShare.setImageUrl(null);
//                    }
//
//                    if (needTextUrl(platform.getName())) {
//                        String sharetext = null;
//                        if (SinaWeibo.NAME.equals(platform.getName())) {
//                            paramsToShare.setText(paramsToShare.getText() + finalUrl1);
//                        } else {
//                            sharetext = text + " \n" + finalUrl1;
//                            paramsToShare.setText(sharetext);
//                        }
//                    }
//                }
//
//                private boolean needTextUrl(String name) {
//                    if ("Wechat".equals(name)) {
//                        return false;
//                    } else if ("WechatMoments".equals(name)) {
//                        return false;
//                    } else if (QQ.NAME.equals(name)) {
//                        return false;
//                    } else if (QZone.NAME.equals(name)) {
//                        return false;
//                    }
//                    return true;
//                }
//            });
//
//            oks.setSilent(false);
//            // 设置自定义的外部回调
//            oks.setCallback(callbackListener);
//            oks.show(context);
//        }
//    }

    //activity destory中调用
    public void destoryShare() {
        ShareSDK.stopSDK(context);
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (context == null) {
            return false;
        }

        switch (msg.what) {
            case MSG_TOAST: {
                String text = String.valueOf(msg.obj);
                Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_ACTION_CCALLBACK: {
                switch (msg.arg1) {
                    case 1: { // 成功
                        showNotification(2000, context.getString(R.string.app_name));
                    }
                    break;
                    case 2: { // 失败
                        String expName = msg.obj.getClass().getSimpleName();
                        if ("WechatClientNotExistException".equals(expName)
                                || "WechatTimelineNotSupportedException".equals(expName)) {
                            showNotification(2000, "WechatClientNotExistException or WechatTimelineNotSupportedException");
                        } else if ("GooglePlusClientNotExistException".equals(expName)) {
                            showNotification(2000, "GooglePlusClientNotExistException");
                        } else if ("QQClientNotExistException".equals(expName)) {
                            showNotification(2000, "GooglePlusClientNotExistException");
                        } else {
                            showNotification(2000, context.getString(R.string.app_name));
                        }
                    }
                    break;
                    case 3: { // 取消
                        showNotification(2000, context.getString(R.string.app_name));
                    }
                    break;
                }
            }
            break;
            case MSG_CANCEL_NOTIFY: {
                NotificationManager nm = (NotificationManager) msg.obj;
                if (nm != null) {
                    nm.cancel(msg.arg1);
                }
            }
            break;
        }
        return false;
    }

    //来自哪个平台的分享，默认0，微信好友,1，微信朋友圈2，QQ3，QQ空间4，新浪微博5，信息6，邮件7，复制链接8
    public void setShareWhere(Platform platform) {
        if (platform != null) {
            if (cn.sharesdk.system.text.ShortMessage.NAME.equals(platform.getName())) {
                shareWhere = "6";
            } else if (cn.sharesdk.system.email.Email.NAME.equals(platform.getName())) {
                shareWhere = "7";
            } else if (Wechat.NAME.equals(platform.getName())) {
                shareWhere = "1";
            } else if (WechatMoments.NAME.equals(platform.getName())) {
                shareWhere = "2";
            } else if (QQ.NAME.equals(platform.getName())) {
                shareWhere = "3";
            } else if (QZone.NAME.equals(platform.getName())) {
                shareWhere = "4";
            } else if (SinaWeibo.NAME.equals(platform.getName())) {
                shareWhere = "5";
            }
        }

    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        Message msg = new Message();
        switch (action) {
            case Platform.ACTION_SHARE:
                setShareWhere(platform);
                int size = res.size();
                if ("SinaWeibo".equals(platform.getName()) && size == 0) {
                    return;
                }
                msg.what = MSG_TOAST;
                msg.obj = context.getString(R.string.share_success);
                break;
            case Platform.ACTION_AUTHORIZING:
                msg.what = MSG_TOAST;
                msg.obj = context.getString(R.string.auth_success);
                break;
            default:
                msg.what = MSG_ACTION_CCALLBACK;
                msg.arg1 = 1;
                msg.arg2 = action;
                msg.obj = platform;
                break;
        }
        UIHandler.sendMessage(msg, this);


    }

    public Account getAccountInfo() {
        Account account = null;
        String account_str = ACache.get(ReaderApplication.applicationContext).getAsString(AppConstants.memberCenter.KEY_CACHE_MY_LOGIN);
        Loger.i("ShareAndBusnessUtils", "ShareAndBusnessUtils" + "-getAccountInfo-" + account_str);
        if (account_str != null && !account_str.trim().equals(""))
            account = Account.objectFromData(account_str);
        return account;
    }

    @Override
    public void onError(Platform platform, int action, Throwable throwable) {
        //throwable.printStackTrace();

        Message msg = new Message();

        switch (action) {
            case Platform.ACTION_SHARE:
                msg.what = MSG_TOAST;
                msg.obj = context.getString(R.string.share_error);
                break;
            case Platform.ACTION_AUTHORIZING:
                msg.what = MSG_TOAST;
                msg.obj = context.getString(R.string.auth_error);
                break;
            default:
                msg.what = MSG_ACTION_CCALLBACK;
                msg.arg1 = 2;
                msg.arg2 = action;
                msg.obj = throwable;
                break;
        }

        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onCancel(Platform platform, int action) {
        Message msg = new Message();
        switch (action) {
            case Platform.ACTION_SHARE:
                // msg.what = MSG_TOAST;
                // msg.obj = context.getString(R.string.share_success);
                break;
            case Platform.ACTION_AUTHORIZING:
                // msg.what = MSG_TOAST;
                // msg.obj = context.getString(R.string.auth_success);
                break;
            default:
                msg.what = MSG_ACTION_CCALLBACK;
                msg.arg1 = 3;
                msg.arg2 = action;
                msg.obj = platform;
                break;
        }

        UIHandler.sendMessage(msg, this);
    }

    public String getPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        } else {
            return context.getApplicationContext().getFilesDir().getAbsolutePath();
        }
        return sdDir.toString();

    }

    private void showNotification(long cancelTime, String text) {
        try {
            Context app = context.getApplicationContext();
            NotificationManager nm = (NotificationManager) app.getSystemService(Context.NOTIFICATION_SERVICE);
            final int id = Integer.MAX_VALUE / 13 + 1;
            nm.cancel(id);

            long when = System.currentTimeMillis();
            Notification notification = new Notification(R.mipmap.ic_launcher, text, when);
            PendingIntent pi = PendingIntent.getActivity(app, 0, new Intent(), 0);
            // notification.setLatestEventInfo(app, context.getText(R.string.app_name), text, pi);
            notification.flags = Notification.FLAG_AUTO_CANCEL;
            nm.notify(id, notification);

            if (cancelTime > 0) {
                Message msg = new Message();
                msg.what = MSG_CANCEL_NOTIFY;
                msg.obj = nm;
                msg.arg1 = id;
                UIHandler.sendMessageDelayed(msg, cancelTime, this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
